package resume_service

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"peilian-api/app/global/common"
	"peilian-api/app/global/log"
	"peilian-api/app/global/variable"
	"peilian-api/app/model"
	"peilian-api/utils/tools"

	"github.com/gin-gonic/gin"
)

// 调用GML结果
func GetGlmResult(ctx *gin.Context, userId uint, id uint, queryType string) (mr model.ResumeResultResp, err error) {
	mr = model.ResumeResultResp{}
	err = nil
	if userId == 0 || id == 0 {
		return mr, err
	}
	reqData, _ := json.Marshal(struct {
		AppId     string `json:"app_id"`
		QueryType string `json:"query_type"`
		UserId    string `json:"user_id"`
	}{
		AppId:     common.GlmYsAppid,
		QueryType: queryType,
		UserId:    fmt.Sprintf("%d_%d", userId, id),
	})
	resp, err := http.Post(
		variable.Config.Services.GetGlmResult,
		"application/json",
		bytes.NewReader(reqData),
	)
	if err != nil {
		log.Logger.ErrorF(ctx, "接口调用失败: "+err.Error())
		return mr, err
	}
	if resp != nil {
		defer resp.Body.Close()
	}
	res := make(map[string]interface{})
	err = tools.ReadResponseBody(resp, &res)
	fmt.Printf("GetGlmResult res: %+v\n", res)
	if err != nil {
		errMsg := "接口响应结果解析失败" + err.Error()
		log.Logger.ErrorF(ctx, errMsg)
		return mr, err
	}
	if code, _ := res["code"].(int64); code != 0 {
		log.Logger.ErrorF(ctx, fmt.Sprintf("接口响应code: %d", code))
		return mr, err
	}

	b, _ := json.Marshal(res["data"])
	_ = json.Unmarshal(b, &mr)
	return mr, nil
}
